package gui.view;

import gui.controller.IllegalUserInputException;

import java.awt.Color;
import java.awt.Component;
import java.awt.GridLayout;

import javax.swing.BorderFactory;
import javax.swing.JPanel;
import javax.swing.JTextField;

import dataTypes.Field;

/**
 * 
 * @author Felix Schliephacke
 * 
 */
public class PlayingSquare extends JPanel {

	private static final long serialVersionUID = -3837341904473187496L;

	public PlayingSquare(Field<Integer>[] square, int columnWidth) {
		this.setLayout(new GridLayout((int) Math.sqrt(square.length),
				(int) Math.sqrt(square.length)));
		this.setBorder(BorderFactory.createLineBorder(Color.BLUE, 2));
		for (Field<Integer> field : square) {
			if (field.size() == 1) {
				this.add(new JTextField(field.get(0).toString(), columnWidth));
			} else {
				this.add(new JTextField(columnWidth));
			}
		}
	}

	public void clear() {
		for (Component temp : this.getComponents()) {
			if (temp instanceof JTextField) {
				((JTextField) temp).setText("");
			}
		}
	}

	public Integer[] getSquare() throws IllegalUserInputException {
		JTextField field;
		Integer[] square = new Integer[this.getComponentCount()];
		int i = 0;
		for (Component temp : this.getComponents()) {
			field = (JTextField) temp;
			if (field.getText().length() == 0) {
				square[i] = null;
			} else {
				try {
					square[i] = Integer.parseInt(field.getText());
					if (square[i] > this.getComponentCount()) {
						throw new IllegalUserInputException(
								"Maximum allowed value is "
										+ this.getComponentCount()
										+ ". Input was " + square[i] + ".");
					} else if (square[i] < 1) {
						throw new IllegalUserInputException(
								"Only positive Integers allowed. Input was "
										+ square[i]);
					}
				} catch (NumberFormatException e) {
					throw new IllegalUserInputException(
							"Only integer values are permitted.");
				}
			}
			i++;
		}
		return square;
	}

}
